package cn.tedu.travelsystem.base.filter;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

@Component
public class SensitiveWordFilter {

    private static final Set<String> SENSITIVE_WORDS = new HashSet<>();

    @PostConstruct
    public void init() {
        try (InputStream is = getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                SENSITIVE_WORDS.add(line.trim());
            }
        } catch (IOException e) {
            throw new RuntimeException("加载敏感词库失败", e);
        }
    }

    public boolean containsSensitiveWord(String text) {
        if (text == null) return false;
        for (String word : SENSITIVE_WORDS) {
            if (text.contains(word)) {
                return true;
            }
        }
        return false;
    }

    public Optional<String> getMatchedWord(String text) {
        for (String word : SENSITIVE_WORDS) {
            if (text.contains(word)) {
                return Optional.of(word);
            }
        }
        return Optional.empty();
    }
}
